package com.ycg.blog.interceptor;

import com.ycg.blog.exception.IpBackException;
import com.ycg.blog.utils.CacheUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author YCG
 * @date 2024-03-14 15:58
 * @description
 */
@Slf4j
@Component
public class IpInterceptor implements HandlerInterceptor {

    @Resource
    private CacheUtil cacheUtil;

    /**
     * 一个ip1秒内的请求限制
     */
    @Value("${site.safe-limit}")
    private Integer safeLimit;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String ip = getIpAddress(request);
        synchronized (ip.intern()) {
            Long count = cacheUtil.getAndIncrement(ip);
            if (count == 1) {
                // 该ip第一次请求
                return true;
            } else if (count >= safeLimit) {
                // 该ip不是第一次请求, 并且超额
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                throw new IpBackException("请求过于频繁, 请稍后再试");
            }
        }
        return true;
    }

    /**
     * 获取真实ip
     *
     * @param request
     * @return
     */
    private static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}